package com.rui.study.algorithm.L_深入理解JVM_JDK动态代理Proxy与cglib;

import net.sf.cglib.core.DebuggingClassWriter;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class TestCglibProxy implements MethodInterceptor {

    static class Bar {
        void dance() {
            System.out.println("Bar.dance()");
        }
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("揍你");
        return methodProxy.invokeSuper(o, objects);
    }


    public Object getProxy(Class target) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(target);
        enhancer.setCallback(this);
        return enhancer.create();
    }

    public static void main(String[] args) {
        // 设置cglib打印的代理类
        System.setProperty(DebuggingClassWriter.DEBUG_LOCATION_PROPERTY, "d:/temp/classes");
        TestCglibProxy testCglibProxy = new TestCglibProxy();
        Bar proxy = (Bar) testCglibProxy.getProxy(Bar.class);
        proxy.dance();
    }
}
